import { createResume, validateResumeContent } from "~/server/database/services/resumeService";
import authMiddleware from "~/server/middleware/auth";

export default defineEventHandler(async (event) => {
  try {
    // 使用认证中间件获取用户信息
    await authMiddleware(event);
    
    const body = await readBody(event);
    const { title, content } = body;
    
    // 从event.context中获取用户信息
    const user = event.context.user;

    // 验证输入数据
    if (!title || typeof title !== 'string' || title.trim().length === 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "标题是必需的且不能为空"
      });
    }

    if (!content || typeof content !== 'string' || content.trim().length === 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "内容是必需的且不能为空"
      });
    }

    // 验证JSON格式
    if (!validateResumeContent(content)) {
      throw createError({
        statusCode: 400,
        statusMessage: "内容必须是有效的JSON格式"
      });
    }

    const resume = await createResume({
      userId: user.id,
      title,
      content
    });
    
    return {
      success: true,
      data: resume,
      message: "简历创建成功"
    };
  } catch (error: any) {
    console.error("创建简历失败:", error);
    if (error.statusCode) {
      throw error;
    }
    throw createError({
      statusCode: 500,
      statusMessage: "创建简历失败"
    });
  }
});
